/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.User;
import pojo.Coupons;
import pojo.UserCoupon;

/**
 *
 * @author A7med Kotb
 */
public class UserCouponJpaController implements Serializable {

    public UserCouponJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(UserCoupon userCoupon) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            User userId = userCoupon.getUserId();
            if (userId != null) {
                userId = em.getReference(userId.getClass(), userId.getId());
                userCoupon.setUserId(userId);
            }
            Coupons couponId = userCoupon.getCouponId();
            if (couponId != null) {
                couponId = em.getReference(couponId.getClass(), couponId.getCId());
                userCoupon.setCouponId(couponId);
            }
            em.persist(userCoupon);
            if (userId != null) {
                userId.getUserCouponCollection().add(userCoupon);
                userId = em.merge(userId);
            }
            if (couponId != null) {
                couponId.getUserCouponCollection().add(userCoupon);
                couponId = em.merge(couponId);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(UserCoupon userCoupon) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            UserCoupon persistentUserCoupon = em.find(UserCoupon.class, userCoupon.getUcId());
            User userIdOld = persistentUserCoupon.getUserId();
            User userIdNew = userCoupon.getUserId();
            Coupons couponIdOld = persistentUserCoupon.getCouponId();
            Coupons couponIdNew = userCoupon.getCouponId();
            if (userIdNew != null) {
                userIdNew = em.getReference(userIdNew.getClass(), userIdNew.getId());
                userCoupon.setUserId(userIdNew);
            }
            if (couponIdNew != null) {
                couponIdNew = em.getReference(couponIdNew.getClass(), couponIdNew.getCId());
                userCoupon.setCouponId(couponIdNew);
            }
            userCoupon = em.merge(userCoupon);
            if (userIdOld != null && !userIdOld.equals(userIdNew)) {
                userIdOld.getUserCouponCollection().remove(userCoupon);
                userIdOld = em.merge(userIdOld);
            }
            if (userIdNew != null && !userIdNew.equals(userIdOld)) {
                userIdNew.getUserCouponCollection().add(userCoupon);
                userIdNew = em.merge(userIdNew);
            }
            if (couponIdOld != null && !couponIdOld.equals(couponIdNew)) {
                couponIdOld.getUserCouponCollection().remove(userCoupon);
                couponIdOld = em.merge(couponIdOld);
            }
            if (couponIdNew != null && !couponIdNew.equals(couponIdOld)) {
                couponIdNew.getUserCouponCollection().add(userCoupon);
                couponIdNew = em.merge(couponIdNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = userCoupon.getUcId();
                if (findUserCoupon(id) == null) {
                    throw new NonexistentEntityException("The userCoupon with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            UserCoupon userCoupon;
            try {
                userCoupon = em.getReference(UserCoupon.class, id);
                userCoupon.getUcId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The userCoupon with id " + id + " no longer exists.", enfe);
            }
            User userId = userCoupon.getUserId();
            if (userId != null) {
                userId.getUserCouponCollection().remove(userCoupon);
                userId = em.merge(userId);
            }
            Coupons couponId = userCoupon.getCouponId();
            if (couponId != null) {
                couponId.getUserCouponCollection().remove(userCoupon);
                couponId = em.merge(couponId);
            }
            em.remove(userCoupon);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<UserCoupon> findUserCouponEntities() {
        return findUserCouponEntities(true, -1, -1);
    }

    public List<UserCoupon> findUserCouponEntities(int maxResults, int firstResult) {
        return findUserCouponEntities(false, maxResults, firstResult);
    }

    private List<UserCoupon> findUserCouponEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(UserCoupon.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public UserCoupon findUserCoupon(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(UserCoupon.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCouponCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<UserCoupon> rt = cq.from(UserCoupon.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
